<template>
  <div class="page">
    <div class="info-message">
      <div class="info-title" v-if="type === 'add'">新增家庭成员</div>
      <div class="info-header" v-else>
        <div class="left">编辑家庭成员信息</div>
        <div class="right" @click="delUser">删除成员</div>
      </div>
      <div class="info-form">
        <van-form ref="dataForm" label-width="35%">
          <van-cell-group inset>
            <van-field v-model="name" label="姓名" placeholder="姓名" required :rules="dataRule.name" />
            <!-- <van-field
              readonly
              v-model="sex"
              is-link
              name="picker"
              label="性别"
              placeholder="点击选择性别"
              @click="showPicker = true"
            />
            <van-popup v-model:show="showPicker" position="bottom">
              <van-picker
                :columns="columns"
                @confirm="onConfirm"
                @cancel="showPicker = false"
              />
            </van-popup> -->
            <van-field v-model="age" label="年龄" type="digit" placeholder="年龄" required :rules="dataRule.age" />
            <custom-select
              :selectId="applyRelationship"
              :columns="relationOption"
              :option="{ label: 'dictionaryName', value: 'dictionaryValue' }"
              :rules="dataRule.applyRelationship"
              required
              label-width="35%"
              label="与申请人关系"
              placeholder="与申请人关系"
              @getValue="getValue"
            ></custom-select>
            <van-field v-model="idcard" label="身份证号" placeholder="身份证号" required maxlength="18" :rules="dataRule.idcard" />
            <custom-select
              :selectId="registeredResidence"
              :columns="areaList"
              :option="{ label: 'regionName', value: 'regionCode' }"
              :rules="dataRule.registeredResidence"
              required
              label="户口所在地"
              placeholder="点击选择户口所在地"
              label-width="30%"
              @getValue="getCountryValue"
            ></custom-select>
          </van-cell-group>
        </van-form>
      </div>
    </div>

    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="toCancel">取消</van-button>
      <van-button type="button" class="cus-btn btn-primary" @click="onSave">保存</van-button>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted, ref, toRefs, computed,getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { Dialog } from 'vant'
import $localStorage from '@/utils/localStorage.js'
export default {
  setup() {
    // 全局属性
    const { $verify } = getCurrentInstance().appContext.config.globalProperties
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const showPicker = ref(false)
    const dataForm = ref(null)
    const columns = ['男', '女']
    const state = reactive({
      name: '',
      age: '',
      sex: '',
      applyRelationship: null,
      idcard: '',
      registeredResidence: null,
      userId: '',
      type: '',
      familyMemberList: [],
      dataRule: {
        name: [{ required: true, message: '请输入申请人姓名', trigger: 'onBlur' }],
        age: [{ required: true, message: '请输入申请人年龄', trigger: 'onBlur' }],
        applyRelationship: [{ required: true, message: '请选择申请人性别', trigger: 'onChange' }],
        idcard: [{ required: true, message: '请输入申请人身份证号', trigger: 'onBlur', validator: $verify.validatorIDcard }],
        registeredResidence: [{ required: true, message: '请选择申请人户口所在地', trigger: 'onChange' }],
      },
    })

    // 获取字典数据
    store.dispatch('getOption', 'APPLY_RELATIONSHIP')
    // 获取字典数据
    store.dispatch('getTownOptions')
    onMounted(() => {
      init()
    })

    const init = async () => {
      const { id, type } = route.query
      state.userId = +id
      state.type = type
      state.familyMemberList = JSON.parse($localStorage.get('familyMemberList'))
      if (state.familyMemberList) {
        if (state.type === 'edit') {
          state.familyMemberList.forEach((res) => {
            if (res.id === state.userId) {
              state.name = res.name
              state.age = res.age
              state.sex = res.sex
              state.applyRelationship = Number(res.applyRelationship)
              state.idcard = res.idcard
              state.registeredResidence = Number(res.registeredResidence)
            }
          })
        }
      } else {
        state.familyMemberList = []
      }
    }
    const goRoute = () => {
      $localStorage.set('familyMemberList', state.familyMemberList)
      router.push({ path: '/build-apply/apply-info' })
    }
    const delUser = () => {
      Dialog.confirm({
        title: '标题',
        message: '确认删除该成员吗?',
      }).then(() => {
        state.familyMemberList = state.familyMemberList.filter((res) => res.id !== state.userId)
        goRoute()
      })
    }
    // 获取户口所在地id
    const getValue = (val) => {
      state.applyRelationship = Number(val)
    }
    // 获取户口所在地id
    const getCountryValue = (val) => {
      state.registeredResidence = Number(val)
    }
    const toCancel = () => {
      router.push({
        path: '/build-apply/apply-info',
      })
    }
    const onConfirm = (value) => {
      state.sex = value
      showPicker.value = false
    }
    // 保存
    const onSave = () => {
      if (state.type === 'add') {
        dataForm.value.validate().then(() => {
          const form = {}
          form.name = state.name
          form.sex = state.sex
          form.age = state.age
          form.applyRelationship = state.applyRelationship
          form.idcard = state.idcard
          form.registeredResidence = state.registeredResidence
          form.id = state.familyMemberList ? state.familyMemberList.length : 0
          state.familyMemberList.push(form)
          goRoute()
        })
      } else {
        dataForm.value.validate().then(() => {
          state.familyMemberList.forEach((res) => {
            if (res.id === state.userId) {
              res.name = state.name
              res.age = state.age
              res.sex = state.sex
              res.applyRelationship = state.applyRelationship
              res.idcard = state.idcard
              res.registeredResidence = state.registeredResidence
            }
          })
          goRoute()
        })
      }
    }

    const relationOption = computed(() => {
      return store.state.option.APPLY_RELATIONSHIP
    })
    const areaList = computed(() => {
      return store.state.townOptions
    })
    return {
      showPicker,
      columns,
      dataForm,
      relationOption,
      ...toRefs(state),
      delUser,
      onConfirm,
      toCancel,
      onSave,
      goRoute,
      getValue,
      getCountryValue,
      areaList,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.page {
  padding-top: 20px;
}
.info-message {
  background: #ffffff;
  border-radius: 15px;
  .info-title {
    padding: 15px;
    font-size: 16px;
    font-weight: bold;
    color: #2e3f6a;
    border-bottom: 1px solid #dee1eb;
  }
  .info-form {
    padding-bottom: 10px;
  }
  .info-header {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    .left {
      font-size: 18px;
      font-weight: bold;
      color: #2e3f6a;
    }
    .right {
      font-size: 16px;
      font-weight: 400;
      color: #ff0000;
    }
  }
  .info-user {
    padding-bottom: 20px;
  }
}
.footer_btn {
  margin: 20px;
  display: flex;
  justify-content: space-between;
  div {
    width: 48%;
  }
}
.btn-group {
  padding: 30px 0 20px;
  .cus-btn {
    width: 167px;
  }
}
</style>